package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rh.bmw4s.R;
import com.rh.bmw4s.bean.ChangeUserInfoBean;
import com.rh.bmw4s.bean.UpLoadImgBean;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.ToastUtils;
import com.rh.bmw4s.utills.glide.GlideImageLoader;
import com.rh.bmw4s.view.PicassoImageLoader;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 个人资料界面
 */
public class PersonalDataActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.edit_info_nick)
    EditText editNick;
    @BindView(R.id.rel_info_head)
    RelativeLayout relHead;
    @BindView(R.id.edit_info_realname)
    EditText editRealname;
    @BindView(R.id.ll_sex_girl)
    LinearLayout llSexGirl;
    @BindView(R.id.ll_sex_boy)
    LinearLayout llSexBoy;
    @BindView(R.id.btn_info_save)
    TextView btnSave;
    @BindView(R.id.tv_info_telnum)
    TextView tvPhone;
    @BindView(R.id.img_info_girl)
    ImageView imgGirl;
    @BindView(R.id.img_info_boy)
    ImageView imgBoy;
    @BindView(R.id.img_info_curhead)
    ImageView imgCurhead;
    @BindView(R.id.rel_info_changphone)
    RelativeLayout relChangphone;

    private GlideImageLoader imageLoader;
    private int anGender = 0;
    private static final int IMAGE_PICKER = 101;
    private Gson gson;
    private String imgPath = "";    //上传图片后，返回的地址


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_data);
        ButterKnife.bind(this);
        gson = new Gson();
        imageLoader = new GlideImageLoader(PersonalDataActivity.this);

        initInfo();
        initPicker();

        //触摸显示光标
        editNick.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    editNick.setCursorVisible(true);
                }
                return false;
            }
        });
        editRealname.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    editRealname.setCursorVisible(true);
                }
                return false;
            }
        });
    }

    private void initPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setMultiMode(false);  //单选
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
//        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
//        imagePicker.setSelectLimit(9);    //选中数量限制
//        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
//        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
//        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
//        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
//        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    /**
     * 从缓存获取信息并展示
     */
    private void initInfo() {

        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("个人资料");

        String strNick = SPUtils.getInstance().getString(ConfigValue.nick);
        String strRelName = SPUtils.getInstance().getString(ConfigValue.relName);
        String strPhone = SPUtils.getInstance().getString(ConfigValue.telPhone);
        String strHeadurl = SPUtils.getInstance().getString(ConfigValue.headUrl);
        anGender = SPUtils.getInstance().getInt(ConfigValue.gender, 0);
        editNick.setText(strNick);//肯定不为空，注册时必填的
        tvPhone.setText(strPhone);
        imageLoader.displayCircle(strHeadurl, imgCurhead);
        if (TextUtils.isEmpty(strRelName)) {
            editRealname.setHint("请输入您的姓名");
        } else {
            editRealname.setText(strRelName);
        }
        if (anGender == 0) { //默认 0 男
            imageLoader.display(imgBoy, R.mipmap.icon_danxuan);
            imageLoader.display(imgGirl, R.mipmap.icon_danxuan_no);
        } else {
            imageLoader.display(imgBoy, R.mipmap.icon_danxuan_no);
            imageLoader.display(imgGirl, R.mipmap.icon_danxuan);
        }


    }


    @OnClick({R.id.title_left_one_btn, R.id.rel_info_head, R.id.rel_info_changphone, R.id.ll_sex_girl, R.id.ll_sex_boy, R.id.btn_info_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                finish();
                break;
            case R.id.rel_info_head:
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                break;
            case R.id.rel_info_changphone:
                startActivityForResult(new Intent(PersonalDataActivity.this, ChangePhoneActivity.class), 13);
                break;
            case R.id.ll_sex_girl:
                anGender = 1;
                imageLoader.display(imgBoy, R.mipmap.icon_danxuan_no);
                imageLoader.display(imgGirl, R.mipmap.icon_danxuan);
                break;
            case R.id.ll_sex_boy:
                anGender = 0;
                imageLoader.display(imgBoy, R.mipmap.icon_danxuan);
                imageLoader.display(imgGirl, R.mipmap.icon_danxuan_no);
                break;
            case R.id.btn_info_save:
                if (checkInfo()) {
                    beginCommit();
                }
                break;
        }
    }

    /**
     * 检验信息
     */
    private boolean checkInfo() {
        String userNick = editNick.getText().toString();
        if (TextUtils.isEmpty(userNick)) {
            ToastUtils.toastForShort(PersonalDataActivity.this, "用户名不能为空");
            return false;
        }
        return true;
    }

    /**
     * 提交用户修改信息
     */
    private void beginCommit() {
        int userId = SPUtils.getInstance().getInt(ConfigValue.userId);
        String strNick = editNick.getText().toString();
        String strRealName = editRealname.getText().toString();

        OkGo.<String>post(Constant.UpLoadUserInfo)
                .tag(PersonalDataActivity.this)
                .params("id", userId)
                .params("username", strNick)
                .params("relname", strRealName)
                .params("gender", anGender)
                .params("logo", imgPath)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d("hhh", response.body().toString());
                        ChangeUserInfoBean bean = gson.fromJson(response.body().toString(), ChangeUserInfoBean.class);
                        if (bean.getStatus() == Constant.SUCESS) {
                            ToastUtils.toastForShort(PersonalDataActivity.this, "修改成功");
                            //发送广播提示修改用户信息
                            Intent intent = new Intent("refreshinfo");
                            intent.putExtra("result", "1");
                            LocalBroadcastManager.getInstance(PersonalDataActivity.this).sendBroadcast(intent);
                            PersonalDataActivity.this.finish();
                        } else {
                            ToastUtils.toastForShort(PersonalDataActivity.this, bean.getMsg());
                        }


                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(PersonalDataActivity.this, "信息上传失败");
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem item = images.get(0);
                upLoadImg(item.path);
            } else {
                ToastUtils.toastForShort(PersonalDataActivity.this, "图片未获取");
            }
        } else if (requestCode == 13 && resultCode == 14) {
            //修改手机号后返回
            String strPhone = SPUtils.getInstance().getString(ConfigValue.telPhone);
            tvPhone.setText(strPhone);
        }
    }

    private void upLoadImg(final String selectPath) {
        DialogUtils.showProgressDlg(PersonalDataActivity.this, "正在上传....");
        OkGo.<String>post(Constant.UpLoadImg)
                .tag(PersonalDataActivity.this)
                .params("logo", new File(selectPath))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("fff", selectPath);
                        LogUtils.d("fff", response.body().toString());
                        UpLoadImgBean imgBean = gson.fromJson(response.body().toString(), UpLoadImgBean.class);
                        if (imgBean.getStatus() == Constant.SUCESS) {
                            imageLoader.displayCircle(selectPath, imgCurhead);
                            imgPath = imgBean.getDatas();
                        } else {
                            ToastUtils.toastForShort(PersonalDataActivity.this, "上传失败");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(PersonalDataActivity.this, "上传失败");
                    }
                });
    }

}
